package com.liyunc.demo.bundle.security.filter;

import com.liyunc.demo.comp.auth.AuthenticatedAccount;
import com.liyunc.demo.comp.auth.AuthenticatedUser;
import com.liyunc.demo.comp.auth.AuthenticationDataLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author liyuncong
 * @version 1.0
 * @file AbstractAuthProvider.java
 * @brief AbstractAuthProvider
 * @details AbstractAuthProvider
 * @date 2022-03-30
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-03-30     liyuncong          Created
 */
public abstract class AbstractAuthProvider implements AuthenticationProvider {

    private final Class<?> authenticationClass;
    @Autowired
    private AuthenticationDataLoader loader;

    public AbstractAuthProvider(Class<?> authenticationClass) {
        this.authenticationClass = authenticationClass;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return this.authenticationClass.equals(authentication);
    }

    protected AuthenticatedAccount<?> buildAuthAccount(AuthenticatedUser<?> user) {
        if (Objects.isNull(user)) {
            return null;
        }
        Iterable<String> roles = loader.getRoles(user);
        List<GrantedAuthority> authorityList = StreamSupport
            .stream(roles.spliterator(), false)
            .map(SimpleGrantedAuthority::new)
            .collect(
                Collectors.toList());
        AuthenticatedAccount<?> account = new AuthenticatedAccount<>(authorityList, user);
        account.setAuthenticated(true);
        return account;
    }
}
